import os
import threading
import time
from datetime import datetime
from datareport.api import ConfigClass
from flask import Blueprint, request, after_this_request

controller=Blueprint('controller', __name__)

@controller.route('/start')
def download():
    print('开始任务')

    ConfigClass.data['year'] = request.args.get('year') if request.args.get('year') else datetime.now().year
    ConfigClass.data['filename'] = request.args.get('filename') if request.args.get('filename') else datetime.now().strftime(
        "%Y%m%d%H%M%S")
    ConfigClass.data['type'] = request.args.get('type') if request.args.get('type') else 'docx'
    print('{}.{}.{}'.format(ConfigClass.data['year'], ConfigClass.data['filename'], ConfigClass.data['type']))

    if request.args.get('type')=='pdf':
        @after_this_request
        def trigger_cleanup(response):
            threading.Thread(target=cleanup).start()
            return response

    from datareport.impl.Application import Application

    return Application().start(ConfigClass.data)

def cleanup():
    time.sleep(10)
    try:
        print('开始删除临时文件')
        os.remove(ConfigClass.data['out_path'] + '/' + ConfigClass.data['filename'] + '.docx')
        os.remove(ConfigClass.data['out_path'] + '/' + ConfigClass.data['filename'] + '.pdf')
        print('删除成功')
    except Exception as e:
        print(f"删除文件失败: {e}")